package com.share.cloudStorage.users.controller;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.share.cloudStorage.constant.Constants;
import com.share.cloudStorage.model.Result;
import com.share.cloudStorage.users.model.Users;
import com.share.cloudStorage.users.service.UsersService;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("api/v1/user")
public class UsersController {

    @Autowired
    private UsersService usersService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    // 获取图形验证码
    @GetMapping("/captcha")
    public void createCaptcha(HttpServletResponse response) throws IOException {
            response.setStatus(HttpServletResponse.SC_CREATED);
            LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(120, 35);
            String captchaId = IdUtil.simpleUUID();
            String code = lineCaptcha.getCode().toLowerCase();
            redisTemplate.opsForValue().set("captcha:" + captchaId, code, 120, TimeUnit.SECONDS);
            // 设置响应头
            response.setHeader("Access-Control-Expose-Headers", "captcha-id");
            response.setHeader("captcha-id", captchaId);
            response.setContentType("image/png");
            BufferedImage image = lineCaptcha.getImage();
            ImageIO.write(image, "png", response.getOutputStream());
    }


    //发送手机验证码
    @PostMapping("/sendCode")
    public Result sendCode(@RequestBody Users user){
        return usersService.sendCode(user);
    }

    // 手机号密码登录
    @PostMapping("/login")
    public Result login(@RequestBody Users user, @RequestParam String captchaCode, @RequestParam String captchaId) {
        return usersService.login(user, captchaCode, captchaId);
    }

    // 手机号验证码登录
    @PostMapping("/logon")
    public Result logon(@RequestBody Users user, @RequestParam String code){
        return usersService.logon(user,code);
    }


    //注册
    @PostMapping("/register")
    public Result register(@RequestBody Users user,@RequestParam String code) throws IOException {
        return usersService.register(user,code);
    }

    //修改用户信息
    @PutMapping("/update")
    public Boolean update(@RequestBody Users users){
        return usersService.updateById(users);
    }

    //获取用户id
    @GetMapping("/getId")
    public Integer getId(HttpServletRequest request) {
        String token = request.getHeader(Constants.TOKEN_KEY);
        JWT jwt = JWTUtil.parseToken(token);

        Object payloadUserId =  jwt.getPayload(Constants.USERNAME_KEY);
        Integer id = ((Number) payloadUserId).intValue();
        log.info("-----------:{}",id);
        return id;
    }

    //获取用户信息
    @GetMapping("/getUser/{userId}")
    public Users getUser(@PathVariable Integer userId){
        return usersService.getUserById(userId);
    }
    //修改用户状态status
    @PostMapping("/updateUserStatus")
    public Result updateUserStatus(@RequestBody Users users){
        return usersService.updateUserStatus(users);
    }
    //添加用户
    @PostMapping("/addUser")
    public Result addUser(@RequestBody Users user){
        String msg = usersService.addUser(user);
        return Result.ok(msg);
    }
    //判断用户是否存在
    @PostMapping("/exists")
    public Boolean exists(@RequestParam("username") String username){
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        Users one = usersService.getOne(queryWrapper);
        if (one!=null){
            return true;
        }else {
            return false;
        }
    }
}